package com.wyu.controller;

import com.wyu.pojo.Cart;
import com.wyu.pojo.Order;
import com.wyu.pojo.OrderItem;
import com.wyu.pojo.User;
import com.wyu.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class OrderController {

    @Autowired
    @Qualifier("OrderServiceImpl")
    private OrderService orderService;

    @RequestMapping("/manager123/order_manager")
    public String order_manager(Model model) {
        List<Order> orders = orderService.showAllOrders();
        model.addAttribute("orders", orders);
        return "manager/order_manager";
    }

    @RequestMapping("/manager123/checkorder/{id}")
    public String checkorder(Model model, @PathVariable String id) {
        List<OrderItem> orderItems= orderService.showOrderDetail(id);
        model.addAttribute("orderItems", orderItems);
        return "order/checkorder";
    }

    @RequestMapping("/manager123/sendOrder/{id}")
    public String sendOrder(Model model, @PathVariable String id) {
        orderService.sendOrder(id);
        return "redirect:/manager123/order_manager";
    }

    @RequestMapping("/user123/order")
    public String order(Model model, HttpSession httpSession) {
        User loginUser = (User) httpSession.getAttribute("user");
        System.out.println(loginUser);
        List<Order> orders = orderService.showMyOrders(loginUser.getId());
        System.out.println(orders);
        model.addAttribute("orders", orders);
        return "order/order";
    }
    @RequestMapping("/user123/receiverOrder/{id}")
    public String receiverOrder(@PathVariable String id) {
        orderService.receiverOrder(id);
        return "redirect:/user123/order";
    }



    //++++++
    @RequestMapping("/user123/createOrder")
    public String createOrder( HttpSession httpSession ) {
        // 先获取Cart购物车对象
        Cart cart = (Cart) httpSession.getAttribute("cart");
        // 获取Userid
        User loginUser = (User) httpSession.getAttribute("user");

        if (loginUser == null) {

            return "user/login";
        }

        Integer userId = loginUser.getId();
//        调用orderService.createOrder(Cart,Userid);生成订单
        String orderId = orderService.createOrder(cart, userId);

//        req.setAttribute("orderId", orderId);
        // 请求转发到/pages/cart/checkout.jsp
//        req.getRequestDispatcher("/pages/cart/checkout.jsp").forward(req, resp);

        httpSession.setAttribute("orderId", orderId);

        return "cart/checkout";
    }
}
